package com.wj.blog.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * 参数验证器配置 hibernate.validator
 *
 * @ClassName ValidatorConfig
 * @Auther: wangjin
 * @Date: 2022/01/11/23:35
 * @Description: 配置快速失败返回模式：只要有一个参数错误就返回
 * @Version 1.0
 */
@Configuration
public class ValidatorConfig {
    /**
     * 用于支持@RequestParam对应的参数的验证<br/>
     * <pre>配置后可在请求参数上使用相应的注解，通过配置全局异常处理来捕获ConstraintViolationException<br/>
     * 注意：需要在方法所在的Controller上加注解@Validated
     * </pre>
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        //设置validator模式为快速失败返回
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        return validatorFactory.getValidator();
    }
}
